package cn.jdemo.ref.WeakReference;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class Demo02 {
    public static void main(String[] args) {
        testWeakReference2();
    }

    /**
     * 弱引用
     * null
     * null
     * [B@2e5c649
     */
    private static void testWeakReference2() {
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            byte[] buff = new byte[1024 * 1024];
            WeakReference<byte[]> sr = new WeakReference<>(buff);
            list.add(sr);
        }

        // System.gc(); //主动通知垃圾回收

        for(int i=0; i < list.size(); i++){
            Object obj = ((WeakReference) list.get(i)).get();
            System.out.println(obj);
        }
    }


    /**
     * 输出:
     * null
     * null
     * null
     * null
     * null
     * null
     * null
     * null
     * null
     * null
     */
    private static void testWeakReference() {
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            byte[] buff = new byte[1024 * 1024];
            WeakReference<byte[]> sr = new WeakReference<>(buff);
            list.add(sr);
        }

        System.gc(); //主动通知垃圾回收

        for(int i=0; i < list.size(); i++){
            Object obj = ((WeakReference) list.get(i)).get();
            System.out.println(obj);
        }
    }
}
